<template>
  <div>
    <div style="margin: 10px">
      <el-row>
        <el-col :span="2">
          <el-upload
              ref="uploadCategory"
              class="upload-demo"
              action="http://localhost:8080/product/category/import"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :headers="header">
            <el-button size="small" type="primary" :icon="Upload">导入</el-button>
            <template #tip>
              <div class="el-upload__tip">
                上传文件大小不能超过100MB.
              </div>
            </template>
          </el-upload>
        </el-col>
        <el-col :span="1">
          <el-button size="small" type="warning" plain :icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table
        :v-loading="loading"
        :data="category.categoryList"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="name" label="分类名称"/>
      <el-table-column prop="imageUrl" label="图标">
        <template #default="scope">
          <img :src="scope.row.imageUrl" style="width: 50px"/>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序"/>
      <el-table-column prop="status" label="状态"/>
      <el-table-column prop="createTime" label="创建时间"/>
    </el-table>
  </div>
</template>

<script setup>
import {Download, Search, Refresh, Upload} from "@element-plus/icons-vue";
import {categoryPinia} from "@/store/product/categoryPinia.js";
import {categoryList} from "@/api/product/category.js";
import {onMounted, ref} from "vue";
import {getToken} from "@/utils/auth.js";
import {ElMessage} from "element-plus";

let category = categoryPinia()
let loading = ref(true)
/** 导入按钮操作 */
let uploadCategory = ref()
let header = reactive({
  Authorization: "Bearer " + getToken()
})
let handleUploadSuccess = (response) => {
  if (response.code === 200) {
    ElMessage.success(response.msg)
    initCategory()
  } else {
    ElMessage.error(response.msg)
  }
  uploadCategory.value.clearFiles()
}
let handleUploadError = (err) => {
  ElMessage.error('网络连接错误，上传失败')
}
/** 导出按钮操作 */
const {proxy} = getCurrentInstance();
let handleExport = () => {
  proxy.download("product/category/export", {}, `商品分类_${new Date().getTime()}.xlsx`);
};
//初始化分类列表
let initCategory = async () => {
  let {data} = await categoryList(0)
  category.categoryList = data
  loading.value = false;
}
//初始化
onMounted(() => {
  initCategory()
})
//懒加载
let load = async (tree, treeNode, resolve) => {
  let {data} = await categoryList(tree.id)
  resolve(data)
}
</script>

<style scoped>

</style>